package br.ufc.si.sax;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import br.ufc.si.model.Orgao;

public class ListarOrgaos extends DefaultHandler {
	private Orgao orgao;
	private ArrayList<Orgao> ListOrgaos = new ArrayList<Orgao>();
	private String temp;

	public ArrayList<Orgao> ListarTodosOrgaos(String codigo_municipio,
			String exercicio) {
		Parser(codigo_municipio, exercicio);
		return ListOrgaos;
	}

	private void Parser(String codigo_municipio, String exercicio) {
		SAXParserFactory spf = SAXParserFactory.newInstance();
		SAXParser parser;
		try {

			parser = spf.newSAXParser();
			parser.parse(
					"http://api.tcm.ce.gov.br/sim/1_0/orgaos.xml?codigo_municipio="
							+ codigo_municipio + "&exercicio_orcamento="
							+ exercicio, this);

		} catch (SAXException e) {
			System.out.println("SAX exception = [[" + e.getMessage() + "]]");
		} catch (IOException e) {
			System.out.println("I/O exception = [[" + e.getMessage() + "]]");
		} catch (ParserConfigurationException e) {
			System.out.println("ParserConfig exception = [[" + e.getMessage()
					+ "]]");
		}
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {

		if (qName.equalsIgnoreCase("orgaos")) {
			orgao = new Orgao();
			orgao.setCodigo_orgao(attributes.getValue("codigo_municipio"));
		}
	}

	public void characters(char[] buffer, int start, int length)
			throws SAXException {
		temp = new String(buffer, start, length);
	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equalsIgnoreCase("orgaos")) {
			// add it to the list
			ListOrgaos.add(orgao);

		} else if (qName.equalsIgnoreCase("nome_orgao")) {
			orgao.setNome_orgao(temp);

		} else if (qName.equalsIgnoreCase("codigo_orgao")) {
			orgao.setCodigo_orgao(temp);
		} 
		
		else if (qName.equalsIgnoreCase("codigo_municipio")) {
			orgao.setCodigo_municipio(temp);
		}

		else if (qName.equalsIgnoreCase("exercicio_orcamento")) {
			orgao.setExercicio_orcamento(temp);
		}

		else if (qName.equalsIgnoreCase("codigo_tipo_unidade")) {
			orgao.setCodigo_tipo_unidade(temp);
		}

		else if (qName.equalsIgnoreCase("cgc_orgao")) {
			orgao.setCgc_orgao(temp);
		}
	}
}
